package com.yicong.ants.ui.circle.article;

import android.content.pm.ActivityInfo;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;

import com.cchao.simplelib.Const;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.ui.web.WebViewFragment;
import com.cchao.simplelib.util.UrlUtil;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.circle.ArticleBean;
import com.yicong.ants.bean.circle.RewardRank;
import com.yicong.ants.bean.coin.TransInfo;
import com.yicong.ants.databinding.AriticleWebActivityBinding;
import com.yicong.ants.databinding.DialogRewardInfoBinding;
import com.yicong.ants.databinding.RewardRankItemBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.http.RetrofitHelper;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jzvd.Jzvd;

/**
 * 文章页
 *
 * @author cch
 * @version 2020/7/14
 */
public class ArticleWebActivity extends BaseTitleBarActivity<AriticleWebActivityBinding> implements View.OnClickListener {

    String mId;
    String mLink;
    ViewGroup mContainer;
    ArticleBean mBean;
    WebViewFragment mWebViewFragment;

    @Override
    protected int getLayout() {
        return R.layout.ariticle_web_activity;
    }

    @Override
    protected void initEventAndData() {
        mId = getIntent().getStringExtra(Constants.Extra.Id);
        mLink = getIntent().getStringExtra(Const.Extra.Web_View_Url);
        mContainer = findViewById(R.id.ad_container);
        setTitleBarVisible(false);
        onLoadData();
        mDataBind.setClick(this);
        initHandler();
    }

    private void initHandler() {
        mWebViewFragment = (WebViewFragment) this.getSupportFragmentManager().findFragmentById(com.cchao.simplelib.R.id.fragment);
        mWebViewFragment.setWebViewHandler((view, url) -> {
            if (url.contains(".com/yc_app/rewardAuthor")
                || (url.contains("/api/v2/web/apps") && "reward_author".equals(UrlUtil.getValueFromUrl(url, "type")))) {
                showRewardAuthor();
                return true;
            }

            if (url.contains(".com/yc_app/user_center")) {
                RxBus.get().postEvent(Constants.Event.Expect_Refresh_Dashboard);
                finish();
                return true;
            }
            return false;
        });
    }

    private void showRewardAuthor() {
        showProgress();
        addSubscribe(RetrofitHelper.getApis().tranInfo(Collections.emptyMap())
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    switchView(NET_ERROR);
                    return;
                }
                showRewardDialog(respBean.getData());
            }, RxHelper.getSwitchErrorConsumer(this)));
    }

    void showRewardDialog(TransInfo transInfo) {
        Dialogs.rewardAuthor(mContext, transInfo, (amount, payPwd) -> {
            showProgress();
            Map<String, String> map = new HashMap<>();
            map.put("pay_pwd", payPwd);
            map.put("amount", amount);
            map.put("office_id", mId);

            addSubscribe(RetrofitHelper.getApis().rewardAuthor(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        UiHelper.showConfirmDialog(mContext, respBean.getMsg(), null);
                        return;
                    }
                    Dialogs.showCommonSuc(mContext, R.drawable.common_agree, respBean.getMsg(), "", null);
                    mWebViewFragment.mWebView.reload();
                }, RxHelper.getHideProgressConsumer(ArticleWebActivity.this)));
        });
    }

    @Override
    protected void onLoadData() {
        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("office_id", mId);
        addSubscribe(RetrofitHelper.getApis().articleDetail(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    return;
                }
                mBean = respBean.getData();
                updateView();
            }, RxHelper.getHideProgressConsumer(this)));
    }

    private void updateView() {
        mDataBind.setBean(mBean);
        mDataBind.likeImage.setImageResource(mBean.getIs_like() == 1 ? R.drawable.circle_liked : R.drawable.circle_unlike);
        if (mBean.getType() == 3) {
            String vUrl = AppHelper.getProxy().getProxyUrl(mBean.getUrls_files().get(0));
            mDataBind.videoPlayer.setUp(vUrl, "", Jzvd.SCREEN_NORMAL);
            UiHelper.setVisibleElseGone(mDataBind.videoField, true);
            ImageHelper.loadImageRound(mDataBind.videoPlayer.posterImageView, mBean.getImage_url(), 4, R.drawable.common_place_holder_pure);
            mDataBind.videoPlayer.startVideo();
        }
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.back) {
            finish();
        } else if (viewId == R.id.share_field || viewId == R.id.share) {
            BusinessHelper.shareWx(this
                , "社区文章"
                , mBean.getTitle()
                , mBean.getImage_url()
                , mLink, () -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("office_id", mId);
                    addSubscribe(RetrofitHelper.getApis().shareCount(map)
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            if (respBean.isCodeSuc()) {
                                onLoadData();
                            }
                        }, RxHelper.getHideProgressConsumer(this)));
                });
        } else if (viewId == R.id.like_field) {
            toggleLike();
        } else if (viewId == R.id.reward_field) {
            // 加载排行榜
            Map<String, String> map = new HashMap<>();
            map.put("office_id", mId);
            addSubscribe(RetrofitHelper.getApis().rewardRank(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        return;
                    }
                    showRewardInfo(respBean.getData());
                }, RxHelper.getHideProgressConsumer(this)));
        } else if (viewId == R.id.video_close) {
           /* if (mDataBind.videoPlayer.isActivated()) {
                mDataBind.videoPlayer.reset();
            }*/
            Jzvd.releaseAllVideos();
            UiHelper.setVisibleElseGone(mDataBind.videoField, false);
        }
    }

    private void showRewardInfo(List<RewardRank> data) {
        BottomSheetDialog dialog = new BottomSheetDialog(mContext);
        DialogRewardInfoBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.dialog_reward_info, null, false);
        binding.setClick(v -> {
            //
            showRewardAuthor();
            dialog.dismiss();
        });

        for (int i = 0; i < data.size(); i++) {
            RewardRankItemBinding bind2 = DataBindingUtil.inflate(mLayoutInflater, R.layout.reward_rank_item, null, false);
            bind2.index.setText(String.valueOf(i + 1));
            bind2.setBean(data.get(i));
            UiHelper.setVisibleElseGone(bind2.index, i >= 3);
            UiHelper.setVisibleElseGone(bind2.rewardLevel, i < 3);
            if (i == 0) {
                bind2.rewardLevel.setImageResource(R.drawable.reward_level_1);
            } else if (i == 1) {
                bind2.rewardLevel.setImageResource(R.drawable.reward_level_2);
            } else if (i == 2) {
                bind2.rewardLevel.setImageResource(R.drawable.reward_level_3);
            }
            binding.linear.addView(bind2.getRoot());
        }

        UiHelper.setVisibleElseGone(binding.noRewardField, CollectionHelper.isEmpty(data));
        UiHelper.setVisibleElseGone(binding.rewardAuthor, CollectionHelper.isNotEmpty(data));
        UiHelper.setVisibleElseGone(binding.scroll, CollectionHelper.isNotEmpty(data));
        binding.scroll.getLayoutParams().height = UiHelper.dp2px(CollectionHelper.isEmpty(data) ? 170 : 290);

        dialog.setContentView(binding.getRoot());
        dialog.show();
    }

    private void toggleLike() {
        Map<String, String> map = new HashMap<>();
        map.put("office_id", mId);
        addSubscribe(RetrofitHelper.getApis().circleLike(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    return;
                }
                onLoadData();
            }, RxHelper.getHideProgressConsumer(this)));
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Jzvd.FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        Jzvd.NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }
}
